//
//  WarnReportControllerViewController.swift
//  vmes
//
//  Created by 志鹏 翟 on 2021/12/2.
//

import UIKit
import Alamofire

class WarnReportController: BaseController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    
    var dataArr  = NSMutableArray()//错误数据源
    var colltionView : UICollectionView?
    
    var machineInfo : MachineInfo?
    var machineDetil : MachineItem?
    
    let imageView = UIImageView()
    let machineNameLb=UILabel()
    let workshopLb=UILabel()
    let desc1=UILabel()
    let desc2=UILabel()
    
    var currentChoose : Int?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title="设备报警"
        view.backgroundColor = .white
        let topLayout=UIView()
        //        topLayout.alpha=0.2
        topLayout.backgroundColor = UIColor.colorWithHex(hexStr: "#3FB59E",alpha: 1)
        topLayout.layer.shadowColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).cgColor
        topLayout.frame=CGRect(x: 10, y: statusBarHeight, width: width-20, height: 175)
        topLayout.layer.cornerRadius=10
        topLayout.layer.shadowOpacity = 1
        topLayout.layer.shadowRadius = 1.5
        view.addSubview(topLayout)
        
        imageView.backgroundColor=UIColor.colorWithHex(hexStr: "#9FDACE")
        imageView.image = imageWithImage(image: UIImage(named: "machine")!, scaledToSize: CGSize(width: 120, height: 90))
        imageView.contentMode = .center
        topLayout.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(10)
            make.width.height.equalTo(135)
        }
        
        
        machineNameLb.font=machineNameLb.font.withSize(22)
        machineNameLb.textColor = .white
        machineNameLb.text="J001"
        topLayout.addSubview(machineNameLb)
        machineNameLb.snp.makeConstraints { make in
            make.left.equalTo(imageView.snp.right).offset(20)
            make.top.equalTo(imageView.snp.top)
        }
        
        workshopLb.font=machineNameLb.font.withSize(15)
        workshopLb.textColor = .white
        workshopLb.text="车间1"
        topLayout.addSubview(workshopLb)
        workshopLb.snp.makeConstraints { make in
            make.left.equalTo(machineNameLb.snp.left)
            make.top.equalTo(machineNameLb.snp.bottom).offset(5)
        }
        
        desc1.font=machineNameLb.font.withSize(15)
        desc1.alpha=0.8
        desc1.textColor = .white
        desc1.text="J001"
        topLayout.addSubview(desc1)
        desc1.snp.makeConstraints { make in
            make.left.equalTo(machineNameLb.snp.left)
            make.top.equalTo(workshopLb.snp.bottom).offset(20)
        }
        
        desc2.font=machineNameLb.font.withSize(15)
        desc2.textColor = .white
        desc2.alpha=0.8
        desc2.text="J001"
        topLayout.addSubview(desc2)
        desc2.snp.makeConstraints { make in
            make.left.equalTo(machineNameLb.snp.left)
            make.top.equalTo(desc1.snp.bottom).offset(5)
        }
        getMachineInfo()
        initView()
    }
    
    func imageWithImage(image: UIImage, scaledToSize: CGSize) -> UIImage? {
        //UIGraphicsBeginImageContext(newSize);
        // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
        // Pass 1.0 to force exact pixel size.
        let radio = image.size.width / image.size.height
        UIGraphicsBeginImageContextWithOptions(scaledToSize, false, 0.0)
        image.draw(in: CGRect(x: 0, y: 0, width: scaledToSize.width * radio, height: scaledToSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
    
    func getMachineInfo(){
        spinner.startAnimating()
        let parameters: Dictionary = [
            "compId":machineInfo?.compId ?? "",
            "equipId":machineInfo?.equipId ?? "",
            "workshopType":K.currentWorkShop?.workshopType ?? ""
        ]
        sessionManager.request(NetInfo.machineDetail, method:.post
                               , parameters:parameters,encoder: JSONParameterEncoder.default,headers: K.headers!).responseJSON { response in
            self.spinner.stopAnimating()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(MachineData.self, from: data)
                    if(response?.code==200){
                        self.machineDetil=response?.data
                        self.initMachineInfo()
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
    }
    
    func initMachineInfo(){
        machineNameLb.text=machineDetil?.equipCode
        workshopLb.text=machineDetil?.workshopName
        desc1.text=machineDetil?.equipName
        desc2.text=machineDetil?.remarkInfo
    }
    
    func initView(){
        let layout = UICollectionViewFlowLayout()
        colltionView = UICollectionView(frame: CGRect(x: 0, y:160+statusBarHeight, width: width, height: 250), collectionViewLayout: layout)
        //注册一个cell
        colltionView!.register(MachineCell.self, forCellWithReuseIdentifier:"cell")
        colltionView?.delegate = self;
        colltionView?.dataSource = self;
        //        colltionView?.backgroundColor = UIColor.whiteColor()
        //设置每一个cell的宽高
        layout.itemSize = CGSize(width: (width-60)/2, height: 30)
        layout.sectionInset = UIEdgeInsets.init(top: 20, left: 10, bottom: 0, right: 10)
        self.view.addSubview(colltionView!)
        
        let btn=UIButton()
        btn.layer.cornerRadius=5
        self.view.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(statusBarHeight+420)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(55)
        }
        btn.setTitle("提交报警原因", for: .normal)
        btn.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        btn.setTitleColor(UIColor.colorWithHex(hexStr: "#ffffff"), for: .normal)
        btn.addTarget(self, action: #selector(submitError), for: .touchUpInside)
        
        getData()
    }
    
    @objc func submitError(){
        print("开工")
        if currentChoose == nil{
            self.view.makeToast("请先选择原因！")
            return
        }
        spinner.startAnimating()
        let reason=dataArr[currentChoose!] as! ErrorInfo
        let parameters: Dictionary = [
            "id" : machineInfo?.id,
            "warningReason" : reason.dictValue,
            "remarkInfo" : "",
        ]
        AF.request(NetInfo.warnSubmit, method:.put
                   , parameters:parameters,encoder: JSONParameterEncoder.default,headers: K.headers!,
                   requestModifier: { $0.timeoutInterval = 5 }).responseJSON { (response) in
            self.spinner.stopAnimating()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(LoginInfo.self, from: data)
                    if(response?.code==200){
                        self.view.makeToast("提交成功",duration:2)
                        self.perform(#selector(self.backItemPressed), with: nil, afterDelay: 2)
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
    }
    
    //返回多少个组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //        print(indexPath.item)
        currentChoose=indexPath.item
        self.colltionView?.reloadData()
        
    }
    
    //返回多少个cell
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    //返回自定义的cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! MachineCell
        let item = dataArr[indexPath.row] as! ErrorInfo
        cell.layer.cornerRadius=12
        if(indexPath.row==currentChoose){
            cell.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        }else{
            cell.backgroundColor = UIColor.colorWithHex(hexStr: "#f3f5f9")
        }
        cell.titleLabel?.text = item.dictLabel
        cell.titleLabel?.font = .systemFont(ofSize: 15)
        return cell
    }
    
    func getData(){
        spinner.startAnimating()
        sessionManager.request(NetInfo.abno, method:.get,headers: K.headers!)
            .responseJSON { response in
                self.spinner.stopAnimating()
                print(response)
                switch response.result {
                case .success:
                    if let data=response.data{
                        let response = try? JSONDecoder().decode(ErrorList.self, from: data)
                        if(response?.code==200){
                            self.dataArr.addObjects(from: (response?.data)!)
                            print(  self.dataArr.count)
                            self.colltionView?.reloadData()
                        }else{
                            self.view.makeToast(response?.msg)
                        }
                    }
                case .failure:
                    print("ERROR")
                    self.view.makeToast("请求失败")
                }
            }
    }
    
}
